/**
 * Copyright (c) OpenSpug Organization. https://github.com/openspug/spug
 * Copyright (c) <spug.dev@gmail.com>
 * Released under the AGPL-3.0 License.
 */
import {observable} from "mobx";
import service from 'libs/request';
import React from "react";
import TableOperation from "../../../components/index/TableOperation";
import FormatPic from "../../../components/formater/FormatPic";
import FormatFile from "../../../components/formater/FormatFile";
import FormatLink from "../../../components/formater/FormatLink";
import FormatRaw from "../../../components/formater/FormatRaw";

class Store {
  //请求的地址
  @observable uri;
  //弹窗配置
  @observable modalConfig = {};
  //询问框配置
  @observable confirmConfig = {};
  //列表
  @observable records = [];
  //一行
  @observable record = {};
  // 搜索表单配置
  @observable searchConfig = [];
  // attributesLabels
  @observable attributesLabels = {};
  // 搜索字段map
  @observable searchMap = {};
  // 表格外部操作配置
  @observable actionDivConfig = [];
  //弹窗显示控制
  @observable modalVisible = false;
  //配置文件的请求地址
  @observable configUri = "";
  //获取配置文件的参数
  @observable configParams = {};

  @observable isFetching = false;
  @observable tableType = "table";
  @observable hasPermissionAction = [];

  //////////////////////////////////////
  //表格相关
  @observable tableColumns = [];
  //默认的每页条数
  @observable defaultPageSize=undefined;
  //总数
  @observable total=0;
  //页码
  @observable page=1;
  //每页大小
  @observable pageSize=10;
  //表格所有选中的id
  @observable selected_ids = [];

  _init = () => {
      this.modalConfig = {};
      this.confirmConfig = {};
      this.records = [];
      this.record = {};
      this.searchConfig = [];
      this.searchMap = {};
      this.actionDivConfig = [];
      this.modalVisible = false;
      this.configUri = "";
      this.configParams = {};
      this.isFetching = false;
      this.tableColumns = [];
      this.defaultPageSize=undefined;
      this.total = 0;
      this.page = 1;
      this.pageSize = 10;
      this.selected_ids = [];
      this.attributesLabels = {};
  };


  //显示弹窗
  showModal = (configUri,configParams={},modalConfig={}) => {
      this.modalVisible = true;
      this.configUri = configUri;
      this.configParams = configParams;
      this.modalConfig = modalConfig;
  };

  resetSearchMap = () => {
     this.searchMap = {};
     this.page = 1;
     this.pageSize = 10;
     this.fetchRecords();
  };

  setSearchMap = (map) => {
     this.searchMap = map;
     this.page = 1;
     this.pageSize=10;
  };

  getSearchResult = () => {
      let searchResult = [];
      Object.keys(this.attributesLabels).forEach(key => {
          searchResult.push({
              "label":this.attributesLabels[key],
              "value":this.searchMap.hasOwnProperty(key) && this.searchMap[key] !== undefined ? (Array.isArray(this.searchMap[key]) ? this.searchMap[key].join("-") : this.searchMap[key] ) : "无",
              "key":key
          })
      });
      return searchResult;
  };

  handleAttributesLabels = (attributesLabels) => {
      if (Array.isArray(attributesLabels)){
          attributesLabels.forEach(item => {
              this.attributesLabels[item["field"]] = item["label"];
          })
      }
  };

  fetchRecords = async () => {
    console.log("请求的首页地址:",this.uri);
    this.isFetching = true;
    this.searchMap["page"] = this.page;
    this.searchMap["pageSize"] = this.pageSize;
    let response = await service.request({
      url:this.uri,
      // url:"/admin/setting/running1/page2/index",
      method:"get",
      params: this.searchMap,
    });

    this.records = response.data.data;
    this.searchConfig = response.data.searchConfig;
    this.handleAttributesLabels(response.data.searchConfig);
    this.actionDivConfig = response.data.actionDivConfig;
    if(response.data.tableType){
        this.tableType = response.data.tableType;
    }else {
        this.tableType = "table"
    }

    //表格相关设置
    this.tableColumns = response.data.tableConfig.columns;
    //处理表格的format
    // eslint-disable-next-line array-callback-return
    this.tableColumns.map(item => {
        // console.log("item",item)
        if (item["format"] === "pic"){
          item["render"] = (text,record) => (
              <FormatPic record={text}/>
          )
        }else if (item["format"] === "file"){
          item["render"] = (text,record) => (
              <FormatFile record={text}/>
          )
        }else if (item["format"] === "link"){
          item["render"] = (text,record) => (
              <FormatLink record={text} title={item["title"]}/>
          )
        }else if (item["format"] === "raw"){
            item["render"] = (text,record) => (
                <FormatRaw record={text}/>
            )
        }
    });

    const config = response.data.tableConfig.actions;
    //拥有权限的操作
    const hasPermissionAction = [];
    config.forEach(item => {
        if (item.auth){
            hasPermissionAction.push(item)
        }
    });
    //没有操作的话，这一栏都不要
    if (hasPermissionAction.length > 0){
        this.tableColumns.push({
            title:"操作",
            width:230,
            //渲染表格操作
            render:(info)=>(
                <TableOperation info={info} config={hasPermissionAction}/>
            )
        });

        this.hasPermissionAction = hasPermissionAction;
    }

    this.total = response.data.pagination.totalCount;

    this.isFetching = false
  };

  showForm = (info = {}) => {
    this.formVisible = true;
    this.record = info
  }
}

export default new Store()
